package tk.djcrazy.instantmessage.daoImpl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import tk.djcrazy.instantmessage.dao.IDao;

public class DaoImpl<T> extends HibernateDaoSupport implements IDao<T>{
	public static Log log = LogFactory.getLog(DaoImpl.class);
	@Override
	@SuppressWarnings("unchecked")
	public T findById(Class<T> clazz, int id) {
		return (T) getHibernateTemplate().load(clazz, id);
	}

	@Override
	public void create(T baseBean) {
		log.debug(baseBean.toString());
		getHibernateTemplate().persist(baseBean);
	}

	@Override
	public List<T> queryList(String hql, Object... params) {
		Session session = getHibernateTemplate().getSessionFactory()
				.getCurrentSession();
		Query query = session.createQuery(hql);
		for (int i = 0; params != null && i < params.length; i++) {
			System.out.println(params.length);
			query.setParameter(i, params[i]);
		}
		@SuppressWarnings("unchecked")
		List<T> list = query.list();
		return list;
	}

	@Override
	public int queryCount(String hql, Object... params) {
		Session session = getHibernateTemplate().getSessionFactory()
				.getCurrentSession();
		Query query = session.createQuery(hql);
		for (int i = 0; params != null && i < params.length; i++) {
			query.setParameter(i, params[i]);
		}
		Number number = (Number) query.uniqueResult();
		return number.intValue();
	}

	@Override
	public void delete(T baseBean) {
		getHibernateTemplate().delete(baseBean);
	}

	@Override
	public List<T> queryList(String hql, int firstResult, int maxResults,
			Object... params) {
		Session session = getHibernateTemplate().getSessionFactory()
				.getCurrentSession();
		Query query = session.createQuery(hql);
		for (int i = 0; params != null && i < params.length; i++) {
			query.setParameter(i, params[i]);
		}
		@SuppressWarnings("unchecked")
		List<T> list = query.setFirstResult(firstResult)
				.setMaxResults(maxResults).list();
		return list;
	}

	@Override
	public void save(T baseBean) {
		getHibernateTemplate().save(baseBean);
	}

	@Override
	public T queryUnique(String hql, Object... params) {
		Session session = getHibernateTemplate().getSessionFactory()
				.getCurrentSession();
		Query query = session.createQuery(hql);
		for (int i = 0; params != null && i < params.length; i++) {
			query.setParameter(i, params[i]);
		}
		@SuppressWarnings("unchecked")
		T t = (T) query.uniqueResult();
		return t;
	}
}
